package com.red.dubbosimulate.framework.protocol.http;

import com.red.dubbosimulate.framework.Invocation;
import com.red.dubbosimulate.framework.register.LocalRegister;
import org.apache.commons.io.IOUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class DispatcherServerHandler {

    public void handler(HttpServletRequest req, HttpServletResponse resp){

        try {
            Invocation invocation = (Invocation)new ObjectInputStream(req.getInputStream()).readObject();
            String interfaceName = invocation.getInterfaceName();
            Class clazz = LocalRegister.get(interfaceName);
            Method method = clazz.getMethod(invocation.getMethodName(), invocation.getParamType());
            String result = (String) method.invoke(clazz.newInstance(), invocation.getParams());
            IOUtils.write(result,resp.getOutputStream());

        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        }

    }
}
